package com.example.controller;

import cn.hutool.core.date.DateUtil;
import com.example.common.Result;
import com.example.dao.BookDao;
import com.example.dao.OtherDao;
import com.example.entity.Book;
import com.example.entity.Other;
import com.example.entity.Reserve;
import com.example.entity.Params;
import com.example.service.ReserveService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


/**
 * 日期：2025/5/11 17:55
 */

@CrossOrigin
@RestController
@RequestMapping("/reserve")
public class ReserveController {

    @Resource
    private ReserveService reserveService;

    @Resource
    private OtherDao otherDao;

    @GetMapping("/search")
    public Result findBySearch(Params params){
        PageInfo<Reserve> info = reserveService.findBySearch(params);
        return Result.success(info);
    }

    // 新增或修改
    @PostMapping
    public Result save(@RequestBody Reserve reserve){
        Other other = otherDao.selectByPrimaryKey(reserve.getOtherId());

        if (other.getNum() == 0){
            return Result.error("商品被预定空了");
        }

        reserve.setTime(DateUtil.now());
        reserveService.add(reserve);

        other.setNum(other.getNum() - 1);
        otherDao.updateByPrimaryKey(other);

        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        reserveService.delete(id);
        return Result.success();
    }
}
